# -*- coding: utf8-*-
_author_ = 'yykrlc'

import six
from app.werobot.WXBizMsgCrypt import WXBizMsgCrypt
from app_config import BaseConfig


token = BaseConfig.open_token
component_appid = BaseConfig.component_appid
component_appsecret = BaseConfig.component_appsecret
encodingAESKey = BaseConfig.encodingAESKey


class WxUtils:
    def get_encrypt_xml(self, reply_xml, nonce):
        reply_xml = reply_xml.encode('utf-8')
        encrypt = WXBizMsgCrypt(token, encodingAESKey, component_appid)
        ret_encrypt, encrypt_xml = encrypt.EncryptMsg(reply_xml, nonce)
        if ret_encrypt == 0:
            return encrypt_xml
        else:
            return str(ret_encrypt) + ' error'
    
    def get_decrypt_xml(self, encrypt_xml, msg_signature, timestamp, nonce):
        decrypt = WXBizMsgCrypt(token, encodingAESKey, component_appid)
        ret_decrypt, decrypt_xml = decrypt.DecryptMsg(encrypt_xml, msg_signature, timestamp, nonce)
        if ret_decrypt == 0:
            return decrypt_xml
        else:
            return str(ret_decrypt) + ' error'


def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_bytes, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.
    If strings_only is True, don't convert (some) non-string-like objects.
    """
    # Handle the common case first for performance reasons.
    if isinstance(s, bytes):
        if encoding == 'utf-8':
            return s
        else:
            return s.decode('utf-8', errors).encode(encoding, errors)
    if isinstance(s, six.memoryview):
        return bytes(s)
    
    if not isinstance(s, six.string_types):
        try:
            if six.PY3:
                return six.text_type(s).encode(encoding)
            else:
                return bytes(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return b' '.join(force_bytes(arg, encoding, strings_only, errors) for arg in s)
            return six.text_type(s).encode(encoding, errors)
    else:
        return s.encode(encoding, errors)


def to_binary(value, encoding="utf-8"):
    if isinstance(value, six.binary_type):
        return value
    if isinstance(value, six.text_type):
        return value.encode(encoding)
    return six.binary_type(value)
